import 'package:flutter/material.dart';
import 'package:flutter_shop/pages/base/base_state.dart';
import 'package:flutter_shop/pages/cart/cart_tab_page/provider/cart_provider.dart';
import 'package:flutter_shop/pages/home/goods_detail/entity/goods_detail_data.dart';
import 'package:flutter_shop/pages/home/goods_detail/goods_detail_contract.dart';
import 'package:flutter_shop/pages/home/goods_detail/goods_detail_presenter.dart';
import 'package:flutter_shop/pages/home/goods_detail/widget/goods_comment_part.dart';
import 'package:flutter_shop/pages/home/goods_detail/widget/goods_detail_part.dart';
import 'package:flutter_shop/pages/home/goods_detail/widget/top_goods_info.dart';
import 'package:flutter_shop/res/colors.dart';
import 'package:flutter_shop/res/dimens.dart';
import 'package:flutter_shop/res/styles.dart';
import 'package:flutter_shop/widget/common_app_bar.dart';
import 'package:flutter_shop/widget/custom_sliver_persistent_header_delegate.dart';
import 'package:flutter_shop/widget/page_state_widget.dart';
import 'package:flutter_shop/widget/water_click.dart';
import 'package:provider/provider.dart';

///商品详情页
class GoodsDetailPage extends StatefulWidget {
  final String goodsId;

  GoodsDetailPage({Key key, this.goodsId}) : super(key: key);

  @override
  _GoodsDetailPageState createState() => _GoodsDetailPageState();
}

class _GoodsDetailPageState
    extends BaseState<GoodsDetailPage, GoodsDetailPresenter>
    with SingleTickerProviderStateMixin
    implements GoodsDetailView {
  TabController _TabController;

  ///商品信息
  GoodsDetailData goodsDetail;

  ///标题
  String title = "";

  List<Widget> _tabs = [
    Text("详情"),
    Text("评论"),
  ];

  @override
  GoodsDetailPresenter createPresenter() => GoodsDetailPresenter();

  @override
  void initState() {
    super.initState();
    _TabController = TabController(length: _tabs.length, vsync: this);
    //初始化一下商品总数量
    Provider.of<CartProvider>(context, listen: false).getCartGoodsList();
  }

  @override
  void buildComplete() {
    super.buildComplete();
    mPresenter.getGoodsDetail(widget.goodsId);
  }

  @override
  Widget build(BuildContext context) {
    Widget child = Gaps.empty;
    if (goodsDetail != null) {
      child = Container(
        child: Column(
          children: <Widget>[
            Expanded(child: _buildScrollPart()),
            _buildBottomNavigator(),
          ],
        ),
      );
    }

    return Scaffold(
      appBar: CommonAppBar(title),
      body: PageStateWidget(
        controller: pageStateController,
        retryClick: () {
          pageStateController.showLoading();
          mPresenter.getGoodsDetail(widget.goodsId);
        },
        child: child,
      ),
    );
  }

  ///滚动部分
  Widget _buildScrollPart() {
    GoodsDetailDataGoodInfo goodInfo = goodsDetail.goodInfo;
    List<GoodsDetailDataGoodComments> goodComments = goodsDetail.goodComments;
    GoodsDetailDataAdvertesPicture advertesPicture =
        goodsDetail.advertesPicture;

    setState(() {
      title = goodInfo?.goodsName ?? "商品详情";
    });

    double _appBarHeight = TopGoodsInfo.height - kToolbarHeight;

    return NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return <Widget>[
          SliverOverlapAbsorber(
            handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
            child: SliverAppBar(
              //去掉此appbar返回按钮
              leading: Text(''),
              backgroundColor: CommonColors.common_bg,
              forceElevated: innerBoxIsScrolled,
              bottom: PreferredSize(
                child: Container(),
                preferredSize: Size.fromHeight(_appBarHeight),
              ),
              //可折叠的部分
              flexibleSpace: Column(
                children: <Widget>[
                  //顶部区域
                  TopGoodsInfo(goodInfo: goodInfo),
                ],
              ),
            ),
          ),
          //这里放tabbar
          SliverPersistentHeader(
            delegate: CustomSliverPersistentHeaderDelegate(
              max: 40,
              min: 40,
              child: Container(
                height: 40,
                color: Colors.white,
                child: TabBar(
                  controller: _TabController,
                  tabs: _tabs,
                  isScrollable: false,
                  indicatorColor: CommonColors.primary,
                  indicatorSize: TabBarIndicatorSize.tab,
                  labelColor: CommonColors.primary,
                  unselectedLabelColor: CommonColors.common_text,
                ),
              ),
            ),
            pinned: true,
          ),
        ];
      },
      body: TabBarView(
        controller: _TabController,
        children: <Widget>[
          GoodsDetailPart(
              richText: goodInfo.goodsDetail,
              pic: advertesPicture.pictureAddress),
          GoodsCommentPart(
              list: goodComments, pic: advertesPicture.pictureAddress),
        ],
      ),
    );
  }

  ///底部导航
  Widget _buildBottomNavigator() {
    GoodsDetailDataGoodInfo goodInfo = goodsDetail.goodInfo;

    int totalCount = Provider.of<CartProvider>(context).totalCount;

    return Container(
      height: 50,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Borders.top,
      ),
      child: Row(
        children: <Widget>[
          Container(
            width: 80,
            alignment: Alignment.center,
            child: Container(
              width: 45,
              height: 45,
              child: Stack(
                children: <Widget>[
                  WaterClick(
                    alignment: Alignment.center,
                    child: Icon(
                      Icons.shopping_cart,
                      color: CommonColors.primary,
                      size: 35,
                    ),
                    onPressed: () {
                      //进入购物车
                      mPresenter.goCartTab();
                    },
                  ),
                  Positioned(
                    right: 0.0,
                    child: Offstage(
                      offstage: totalCount == 0,
                      child: Container(
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: CommonColors.primary,
                          borderRadius: BorderRadius.circular(20),
                          border: Border.all(width: 1, color: Colors.white),
                        ),
                        width: 20,
                        height: 20,
                        child: Text(
                          "${totalCount > 99 ? '99+' : totalCount}",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: CommonDimens.font_size_xsmall,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: RawMaterialButton(
              onPressed: () {
                //添加商品到购物车
                mPresenter.addGoodsToCart(goodInfo);
              },
              fillColor: CommonColors.green,
              child: Container(
                alignment: Alignment.center,
                height: 50,
                child: Text(
                  "加入购物车",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
          Expanded(
            child: RawMaterialButton(
              onPressed: () {
                //立即购买
                mPresenter.nowBuy(goodInfo);
              },
              fillColor: CommonColors.red,
              child: Container(
                alignment: Alignment.center,
                height: 50,
                child: Text(
                  "立即购买",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _TabController.dispose();
    super.dispose();
  }

  @override
  void showPageData(GoodsDetailData data) {
    pageStateController.showSuccess();
    super.setState(() {
      goodsDetail = data;
    });
  }

  @override
  void showError(String str) {
    pageStateController.showError(str);
    showToast(str);
  }
}
